package com.zzk.lanouhn.myapplication1.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.adapters.FindDetailsCaiDanAdapter;
import com.zzk.lanouhn.myapplication1.adapters.FindDetailsShiShiAdapter;
import com.zzk.lanouhn.myapplication1.intefaces.FindDetailsCaiDanOnItemClicklistener;
import com.zzk.lanouhn.myapplication1.modles.FindDetailsModle;

import java.io.IOException;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/9/3.
 */
public class FindDetailsActivity extends Activity implements FindDetailsCaiDanOnItemClicklistener {

    private RecyclerView recyclerView1;

    private FindDetailsShiShiAdapter adapter;
    private FindDetailsModle modle;
    //控件
    private ImageView iv_shou, iv_fen, iv_zhen_shoucang;

    //菜单
    private RecyclerView caiRecyclerView;
    private FindDetailsCaiDanAdapter caiDanDayAdapter;

    private RelativeLayout ll_caidan;

    private String stringId;
    private String xiaotuID;
    private String zhengID;

    private LinearLayout ll_fanhui;
    //点击菜单出现
    private ImageView iv_caidan;

    LinearLayoutManager layoutManager;

    //是否登录
    private SharedPreferences sp;
    private String login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detailed_find);
        recyclerView1 = (RecyclerView) findViewById(R.id.detailed_find_recyclerView_ha);
        ll_fanhui = (LinearLayout) findViewById(R.id.detailed_find_fanhui);

        caiRecyclerView = (RecyclerView) findViewById(R.id.detailed_find_caidan_recyclerView);
        ll_caidan = (RelativeLayout) findViewById(R.id.detailed_find_caidan_ll);
        iv_caidan = (ImageView) findViewById(R.id.detailed_find_caidan);

        iv_shou = (ImageView) findViewById(R.id.detailed_find_shou);
        iv_fen = (ImageView) findViewById(R.id.detailed_find_fengxiang);
        iv_zhen_shoucang = (ImageView) findViewById(R.id.detailed_find_zhen_shou);

        //得到一级页面传的值
        stringId = getIntent().getStringExtra("id");
        //得到从小图的二级页面传来的值
        xiaotuID = getIntent().getStringExtra("xiaotu_ID");

        if (xiaotuID != null) {
            zhengID = xiaotuID;
        }
        if (stringId != null) {
            zhengID = stringId;
        }

        sp = getSharedPreferences("login", MODE_PRIVATE);
        login = sp.getString("shifou", "false");

        initDate();
        getDataDetails();
        getDataCaidanDetails();
        initEvent();
    }


    private void initDate() {

        ll_fanhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回
                finish();
            }
        });

        iv_caidan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //菜单出现
                ll_caidan.setVisibility(View.VISIBLE);
                iv_caidan.setVisibility(View.GONE);
            }
        });

        //分享
        iv_fen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        //收藏
        iv_shou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (login.equals("false")) {
                    Intent intent = new Intent(FindDetailsActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(FindDetailsActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                    iv_zhen_shoucang.setVisibility(View.VISIBLE);
                }
            }
        });
        //取消收藏
        iv_zhen_shoucang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_shou.setVisibility(View.VISIBLE);
                Toast.makeText(FindDetailsActivity.this, "取消收藏", Toast.LENGTH_SHORT).show();
                iv_zhen_shoucang.setVisibility(View.GONE);
            }
        });

    }

    private void getDataCaidanDetails() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                String url = "http://chanyouji.com/api/trips/ " + zhengID + ".json";

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();

                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(4);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String ss = response.body().string();

                        Gson gson = new Gson();

                        modle = gson.fromJson(ss, FindDetailsModle.class);
                        if (modle.getTrip_days().size() > 0) {
                            handler.sendEmptyMessage(5);
                        } else {
                            handler.sendEmptyMessage(6);
                        }

                    }
                });
            }
        }).start();

    }


    private void getDataDetails() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "http://chanyouji.com/api/trips/ " + zhengID + ".json";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();

                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(3);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        String ss = response.body().string();

                        Gson gson = new Gson();
                        modle = gson.fromJson(ss, FindDetailsModle.class);

                        if (modle.getTrip_days().size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(2);
                        }

                    }
                });
            }
        }).start();
    }


    private void initEvent() {


        ll_caidan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //菜单消失
                ll_caidan.setVisibility(View.GONE);
                iv_caidan.setVisibility(View.VISIBLE);
            }
        });


//        caiRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                int n = layoutManager.findFirstVisibleItemPosition();
//                recyclerView1.scrollToPosition(n);
//                recyclerView1.smoothScrollToPosition(n);
//
//                adapter.notifyDataSetChanged();
//
//            }
//        });

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    adapter = new FindDetailsShiShiAdapter(FindDetailsActivity.this, modle);
                    recyclerView1.setAdapter(adapter);

                    LinearLayoutManager llm = new LinearLayoutManager(FindDetailsActivity.this);
                    recyclerView1.setLayoutManager(llm);
                    break;
                case 2:
                    Toast.makeText(FindDetailsActivity.this, "卧槽，又错了", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(FindDetailsActivity.this, "失败", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(FindDetailsActivity.this, "菜单出错了", Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    caiDanDayAdapter = new FindDetailsCaiDanAdapter(FindDetailsActivity.this, modle);
                    caiRecyclerView.setAdapter(caiDanDayAdapter);

                    //绑定点击事件
                    caiDanDayAdapter.setMyOnItemClick(FindDetailsActivity.this);

                    layoutManager = new LinearLayoutManager(FindDetailsActivity.this);
                    caiRecyclerView.setLayoutManager(layoutManager);

                    break;
                case 6:
                    Toast.makeText(FindDetailsActivity.this, "卧槽，菜单出错了", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }


    //菜单的点击事件,控制滚动的位置
    @Override
    public void myOntemClick(int positoin) {
        recyclerView1.scrollToPosition(positoin + 1);
        adapter.notifyDataSetChanged();

        //菜单消失
        ll_caidan.setVisibility(View.GONE);
        iv_caidan.setVisibility(View.VISIBLE);

    }
}
